/*
 * 标题:          农务数据库检索系统
 * 
 * 描述:  		  以mysql为数据库，远程连接数据库进行水稻、 小麦、昆虫等数据库的检索
 * 
 * 备注:			 demo开头的html、jsp和java文件均为测试用例，无实际效用
 *
 * Copyright (c) 2017, Nanjing Agricultural University, China
 */

package cn.edu.njau.ads.view;

import java.util.HashMap;
import java.util.Map;

import com.opensymphony.xwork2.ActionSupport;

import cn.edu.njau.ads.control.PestControl;
import cn.edu.njau.ads.model.Pest;
import cn.edu.njau.ads.util.AppException;
import net.sf.json.JSONObject;

/**
 * Ajax,昆虫检索
 * 
 * @author zzy
 *
 */
public class SearchPestAction extends ActionSupport{

	private static final long serialVersionUID = 1L;
	
	private String name_cn;  
    private String name_latin;  
    private String _class;
    private String order;
    private String family;
    
    private String result;

    // Ajax 赋值
    public void setName_cn(String name_cn) {
		this.name_cn = name_cn;
	}

	public void setName_latin(String name_latin) {
		this.name_latin = name_latin;
	}

	public void set_class(String _class) {
		this._class = _class;
	}

	public void setOrder(String order) {
		this.order = order;
	}

	public void setFamily(String family) {
		this.family = family;
	}

	// ajax返回结果  
    public String getResult() {  
        return result;  
    } 
	
	/**
	 * 操作执行
	 */
	@Override
	public String execute(){
			// System.out.print(name_cn+name_latin+_class+order+family);
		
			PestControl pestControl = new PestControl();
			
			//将数据存储在map里，再转换成json类型数据，也可以自己手动构造json类型数据
			Map<String,Object> map = new HashMap<String,Object>();
			
			try {
				Pest[] pests = pestControl.SearchPest(name_cn, name_latin, _class, order, family);
				if(pests != null){
					map.put("length", pests.length);
					
					// System.out.println(pests.length);
					
					for(int i=0;i<pests.length;i++){
						map.put("id"+i,pests[i].getId());
						map.put("nc"+i,pests[i].getName_cn());
						map.put("nl"+i,pests[i].getName_latin());
						map.put("_class"+i,pests[i].get_class());
						map.put("order"+i,pests[i].getOrder());
						map.put("family"+i,pests[i].getFamily());
					}
					
					// System.out.println(pests[0].getId());				
				}else{
					// System.out.println("无查询结果");
					map.put("length",0);
				}
				JSONObject json = JSONObject.fromObject(map);//将对象转换成json类型数据
				result = json.toString();//给result赋值，传递给页面
			} catch (AppException e) {
				e.printStackTrace();
				return "404";
			}
	        return SUCCESS;
	}
}
